package com.carepad.action.signin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.carepad.entity.Users;
import com.carepad.service.impl.UsersServiceImpl;
import com.carepad.action.AbstractAction;
import com.carepad.exception.SessionNotExist;
import com.carepad.util.SessionKey;

@Scope("prototype")
public class SignInAction extends AbstractAction {

	@Autowired
	private UsersServiceImpl usersServiceImpl;

	private static final long serialVersionUID = 1L;

	private Users users;

	public String showSigninForm() {
		return SUCCESS;
	}

	public String signIn() {
		try {
			
			validateSignIn();
			
			if (hasErrors()) {
				return INPUT;
			}
			
			users = usersServiceImpl.signIn(users.getAccount(), users.getPassword());
			
			if (users == null) {
				addActionError(getText("user.signin.failed"));
				return INPUT;
			}
			
			addSessionUserVariable(users);
			return SUCCESS;
			
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(getText("user.signin.failed"));
			return INPUT;
		}
	}

	public String signOut() {
		try {
			if (verifySessionUser()) {
				removeSessionVariable(SessionKey.SESSION_USER);
			}
		} catch (SessionNotExist e) {
			e.printStackTrace();
			addActionError(getText("user.not.signin"));
		}

		return SUCCESS;
	}

	private void validateSignIn() {
		
		if (users == null) {
			addActionError(getText("user.signin.failed"));
		}
		else{		
			if (users.getAccount().isEmpty()) {
				addFieldError("users.account",
						getText("user.username.empty"));
			}
	
			if (users.getPassword().isEmpty()) {
				addFieldError("users.password",
						getText("user.password.empty"));
			}
		}
	}

	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

}
